package org.dromara.oce.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bytedance.ads.model.DpaProductAvailablesV2ResponseDataListInner;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.oce.domain.OceProductStore;
import org.dromara.oce.domain.bo.OceProductStoreBo;
import org.dromara.oce.domain.qo.OceProductStoreQo;
import org.dromara.oce.domain.vo.OceProductStoreVo;
import org.dromara.oce.mapper.OceProductStoreMapper;
import org.dromara.oce.service.OceProductStoreService;
import org.dromara.oce.service.remote.OceanEngineThirdRemoteService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品库Service业务层处理
 *
 * @author dsbb
 * @date 2025-06-09
 */
@RequiredArgsConstructor
@Service
public class OceProductStoreServiceImpl extends ServiceImpl<OceProductStoreMapper, OceProductStore> implements OceProductStoreService {

    private final OceProductStoreMapper baseMapper;
    private final OceanEngineThirdRemoteService oceanEngineThirdRemoteService;

    /**
     * 查询商品库
     *
     * @param platformId 主键
     * @return 商品库
     */
    @Override
    public OceProductStoreVo queryById(Long platformId) {
        return baseMapper.selectVoById(platformId);
    }

    /**
     * 分页查询商品库列表
     *
     * @param qo        查询条件
     * @param pageQuery 分页参数
     * @return 商品库分页列表
     */
    @Override
    public TableDataInfo<OceProductStoreVo> queryPageList(OceProductStoreQo qo, PageQuery pageQuery) {
        LambdaQueryWrapper<OceProductStore> lqw = buildQueryWrapper(qo);
        Page<OceProductStoreVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的商品库列表
     *
     * @param qo 查询条件
     * @return 商品库列表
     */
    @Override
    public List<OceProductStoreVo> queryList(OceProductStoreQo qo) {
        LambdaQueryWrapper<OceProductStore> lqw = buildQueryWrapper(qo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OceProductStore> buildQueryWrapper(OceProductStoreQo qo) {
        LambdaQueryWrapper<OceProductStore> lqw = Wrappers.lambdaQuery();
        lqw.eq(qo.getAccountId() != null, OceProductStore::getAccountId, qo.getAccountId());
        lqw.eq(qo.getAdvertiserId() != null, OceProductStore::getAdvertiserId, qo.getAdvertiserId());
        lqw.like(StringUtils.isNotBlank(qo.getName()), OceProductStore::getName, qo.getName());
        lqw.eq(StringUtils.isNotBlank(qo.getProductIndustry()), OceProductStore::getProductIndustry, qo.getProductIndustry());
        return lqw;
    }

    /**
     * 新增商品库
     *
     * @param bo 商品库
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(OceProductStoreBo bo) {
        OceProductStore add = MapstructUtils.convert(bo, OceProductStore.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setPlatformId(add.getPlatformId());
        }
        return flag;
    }

    /**
     * 修改商品库
     *
     * @param bo 商品库
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(OceProductStoreBo bo) {
        OceProductStore update = MapstructUtils.convert(bo, OceProductStore.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OceProductStore entity) {
    }

    /**
     * 校验并批量删除商品库信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public void syncProductStore(Long accountId, List<Long> advertiserIds) {
        String key = "000000:sys_config";
        Map<String, String> map = RedisUtils.getCacheMap(key);
        if (CollectionUtils.isNotEmpty(map)) {
            String idStr = String.valueOf(map.getOrDefault("oce.syncProductStore.advertiserIds", null));
            if (idStr != null) {
                advertiserIds = Arrays.stream(idStr.split(",")).map(String::trim).map(item -> Long.parseLong(item)).collect(Collectors.toList());
            }
        }

        //数据库存在的商品库ID
        List<Long> existList = this.list().stream().map(item -> item.getPlatformId()).collect(Collectors.toList());

        List<OceProductStore> addList = new ArrayList<>();
        for (Long advertiserId : advertiserIds) {
            List<DpaProductAvailablesV2ResponseDataListInner> list = oceanEngineThirdRemoteService.getDptProductAvailablesList(accountId, advertiserId);
            if (list != null && list.size() > 0) {
                for (DpaProductAvailablesV2ResponseDataListInner dd : list) {
                    if (existList.contains(dd.getPlatformId())) {
                        continue;
                    }
                    OceProductStore data = BeanUtil.copyProperties(dd, OceProductStore.class);
                    data.setAdvertiserId(advertiserId);
                    data.setAccountId(accountId);
                    addList.add(data);
                }
            }
        }
        if (addList.size() > 0) {
            this.saveBatch(addList);
        }
    }


}
